<?php

namespace app\mingteng\controller;

use think\AjaxPage;
use think\Db;

class Coach extends Base
{
    public $listRows = 20;

    public function index(){
        $shopList = Db::name('shop')->where('shopIsDel', '=', '0')->select();
        $this->assign('shopList', $shopList);

        return $this->fetch();
    }

    public function ajax_index(){
        $params = input('post.');
        $page = input('page', '1');

        $where = array();
        $where['coachIsDel'] = array('=', '0');
        if (isset($params['keywords']) && !empty($params['keywords'])) {
            $where['c.coachName'] = array('like', '%'.$params['keywords'].'%');
        }
        if (isset($params['shopId']) && !empty($params['shopId'])) {
            $where['c.coachShopId'] = array('=', $params['shopId']);
        }

        $count = Db::name('coachs')->alias('c')->where($where)->count();
        $list = Db::name('coachs')->alias('c')
            ->join('shop s', 'c.coachShopId = s.shopId')
            ->where($where)
            ->field('c.*,s.shopName')
            ->page($page, $this->listRows)->select();
        $this->assign('list', $list);

        $ajaxPage = new AjaxPage($count, $this->listRows);
        $show = $ajaxPage->show();
        $this->assign('page', $show);

        return $this->fetch();
    }

    public function add(){
        $shopList = Db::name('shop')->where('shopIsDel', '=', '0')->select();
        $user = Db::name('user')->where('userStatus',1)->field('userId,nickName,userMobile')->select();
        $this->assign('shopList', $shopList);
        $this->assign('user', $user);

        return $this->fetch();
    }

    public function doAdd(){
        $params = input('post.');

        if (empty($params['userId'])) {
            return json(array('code' => 500, 'msg' => '请绑定用户'));
        }
        if (empty($params['coachName'])) {
            return json(array('code' => 500, 'msg' => '请输入教练名称'));
        }
        if (empty($params['coachPicture'])) {
            return json(array('code' => 500, 'msg' => '请上传教练头像'));
        }
        // if (empty($params['coachImg'])) {
        //     return json(array('code' => 500, 'msg' => '请上传教练静态横图'));
        // }
        if (empty($params['coachRank'])) {
            return json(array('code' => 500, 'msg' => '请输入教练职称/职级'));
        }
        if (empty($params['coachLabel'])) {
            return json(array('code' => 500, 'msg' => '请输入教练标签'));
        }
        if (empty($params['coachShopId'])) {
            return json(array('code' => 500, 'msg' => '请选择教练所属门店'));
        }
        if(empty($params['coach_balance']) || $params['coach_balance'] < 0){
            return json(array('code' => 500, 'msg' => '请输入正确余额'));
        }

        $catch = array(
            'coachName' => $params['coachName'],
            'coachPicture' => config('site_url.site_url') . $params['coachPicture'],
            'coachImg' => config('site_url.site_url') . $params['coachImg'],
            'coachRank' => $params['coachRank'],
            'coachLabel' => $params['coachLabel'],
            'coachContent' => !empty($params['coachContent']) ? $params['coachContent'] : false,
            'coachSort' => $params['coachSort'],
            'coachShopId' => $params['coachShopId'],
            'coachStatus' => $params['coachStatus'],
            'coach_balance' => $params['coach_balance'],
            'userId' => $params['userId'],
        );
        Db::name('coachs')->insertGetId($catch);
        return json(array('code' => 200, 'msg' => '添加成功'));
    }

    public function edit(){
        $coachId = input('coachId');

        $shopList = Db::name('shop')->where('shopIsDel', '=', '0')->select();
        $this->assign('shopList', $shopList);

        $user = Db::name('user')->where('userStatus',1)->field('userId,nickName,userMobile')->select();
        $detail = Db::name('coachs')->where('coachId', '=', $coachId)->find();
        $this->assign('detail', $detail);
        $this->assign('user', $user);

        return $this->fetch();
    }

    public function doEdit(){
        $params = input('post.');

        if (empty($params['userId'])) {
            return json(array('code' => 500, 'msg' => '请绑定用户'));
        }

        if (empty($params['coachName'])) {
            return json(array('code' => 500, 'msg' => '请输入教练名称'));
        }
        if (empty($params['coachPicture'])) {
            return json(array('code' => 500, 'msg' => '请上传教练头像'));
        }
        if (empty($params['coachImg'])) {
            return json(array('code' => 500, 'msg' => '请上传教练静态横图'));
        }
        if (empty($params['coachRank'])) {
            return json(array('code' => 500, 'msg' => '请输入教练职称/职级'));
        }
        if (empty($params['coachLabel'])) {
            return json(array('code' => 500, 'msg' => '请输入教练标签'));
        }
        if (empty($params['coachShopId'])) {
            return json(array('code' => 500, 'msg' => '请选择教练所属门店'));
        }

        $data = Db::name('coachs')->where('coachId',$params['coachId'])->find();
        if($data['coach_balance'] != $params['coach_balance']){
            $params['coach_balance'] = $params['coach_balance'] + $data['coach_balance'];
        }

        $params['coachPicture'] = strstr($params['coachPicture'],"public");
        $params['coachImg'] = strstr($params['coachImg'],"public");
        $catch = array(
            'coachName' => $params['coachName'],
            'coachPicture' => config('site_url.site_url') . '/' . $params['coachPicture'],
            'coachImg' => config('site_url.site_url') . '/' . $params['coachImg'],
            'coachRank' => $params['coachRank'],
            'coachLabel' => $params['coachLabel'],
            'coachContent' => !empty($params['coachContent']) ? $params['coachContent'] : false,
            'coachSort' => $params['coachSort'],
            'coachShopId' => $params['coachShopId'],
            'coachStatus' => $params['coachStatus'],
            'coach_balance' => $params['coach_balance'],
            'userId' => $params['userId'],
        );
        Db::name('coachs')->where('coachId', '=', $params['coachId'])->save($catch);
        return json(array('code' => 200, 'msg' => '编辑成功'));
    }

    public function del(){
        $del_id = input('del_id');

        Db::name('coachs')->where('coachId', '=', $del_id)->save(array(
            'coachIsDel' => '1',
        ));
        return json(array('code' => 200, 'msg' => '操作成功'));
    }

    public function student(){

        $coachId = input('coachId');
        $this->assign('coachId', $coachId);
        return $this->fetch();
    }

    /**
     * 学员列表
     * @return mixed|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function ajax_student(){

        $coachId = input('coachId');
        $keywords = input('keywords');
        $courseType = input('courseType');
        $page = input('page','1');
        if(empty($coachId)){
            return json(array('code' => 500, 'msg' => '教练id不能为空'));
        }
        $where=[];
        if (isset($keywords) && !empty($keywords)) {
            $where['u.nickName'] = array('like', '%'.$keywords.'%');
        }
        if($courseType){
            $where['r.courseType'] = $courseType;
        }

        $where['a.orderCoachId'] = $coachId;
        $student= Db::name('order_course')->alias('a')
            ->join('coach_course r','r.courseId = a.orderCoachCourseId','LEFT')
            ->join('user u','u.userId = a.userId','LEFT')
            ->where($where)
            ->where('a.orderStatus','in',[1,3])
            ->group('a.userId')
            ->field('a.userId,u.nickName,u.avatarUrl,u.gradeName')
            ->page($page, $this->listRows)
            ->select();

        $this->assign('student', $student);

        return $this->fetch();
    }


    public function course(){
        $coachList = Db::name('coachs')->where('coachIsDel', '=', '0')->select();
        $this->assign('coachList', $coachList);

        return $this->fetch();
    }

    public function ajax_course(){
        $params = input('post.');
        $page = input('page', '1');

        $where = array();
        $where['courseIsDel'] = array('=', '0');
        if (isset($params['keywords']) && !empty($params['keywords'])) {
            $where['cc.courseTitle'] = array('like', '%'.$params['keywords'].'%');
        }
        if (isset($params['courseCoachId']) && !empty($params['courseCoachId'])) {
            $where['cc.courseCoachId'] = array('=', $params['courseCoachId']);
        }

        $count = Db::name('coach_course')->alias('cc')->where($where)->count();
        $list = Db::name('coach_course')->alias('cc')
            ->join('coachs c', 'cc.courseCoachId = c.coachId')
            ->where($where)
            ->field('cc.*,c.coachName')
            ->page($page, $this->listRows)->select();
        $this->assign('list', $list);

        $ajaxPage = new AjaxPage($count, $this->listRows);
        $show = $ajaxPage->show();
        $this->assign('page', $show);

        return $this->fetch();
    }

    public function addCourse(){
        $coachList = Db::name('coachs')->where('coachIsDel', '=', '0')->select();
        $this->assign('coachList', $coachList);

        return $this->fetch('add_course');
    }

    public function doAddCourse(){
        $params = input('post.');

        if (empty($params['courseType'])) {
            return json(array('code' => 500, 'msg' => 'error:课程类型为空'));
        }
        if (empty($params['courseTitle'])) {
            return json(array('code' => 500, 'msg' => 'error:课程名称为空'));
        }
        if (empty($params['coursePrice']) || $params['coursePrice'] <= 0) {
            return json(array('code' => 500, 'msg' => 'error:课程价格设置错误'));
        }
        if (empty($params['joint_number']) || $params['joint_number'] <= 0) {
            return json(array('code' => 500, 'msg' => 'error:课程节数设置错误'));
        }
        if (empty($params['courseCoachId'])) {
            return json(array('code' => 500, 'msg' => 'error:课程教练未设置'));
        }

        $courseCoachId = explode(',',$params['courseCoachId']);

        $coach = Db::name('coachs')
            ->where('coachId', 'in', $courseCoachId)
            ->where('coachIsDel', '=', '0')
            ->find();
        if (empty($coach)) {
            return json(array('code' => 500, 'msg' => 'error:选择的教练出错啦'));
        }

        $catch = array(
            'courseType' => $params['courseType'],
            'courseShopId' => $coach['coachShopId'],
            'courseCoachId' => $params['courseCoachId'],
            'courseLogo' => !empty($params['courseLogo']) ? config('site_url.site_url') . $params['courseLogo'] : config('site_url.site_url') . "/public/images/logo.png",
            'courseTitle' => $params['courseTitle'],
            'courseDescribe' => !empty($params['courseDescribe']) ? $params['courseDescribe'] : false,
            'coursePrice' => $params['coursePrice'],
            'courseSort' => $params['courseSort'],
            'courseStatus' => $params['courseStatus'],
            'joint_number' => $params['joint_number'],
        );
        Db::name('coach_course')->insertGetId($catch);
        return json(array('code' => 200, 'msg' => '添加成功'));
    }

    public function editCourse(){
        $courseId = input('courseId');

        $coachList = Db::name('coachs')->where('coachIsDel', '=', '0')->select();
        $this->assign('coachList', $coachList);
        $detail = Db::name('coach_course')
            ->where('courseId', '=', $courseId)
            ->find();
        $courseCoachId  = explode(',',$detail['courseCoachId']);
        $coachName = Db::name('coachs')->where('coachId','in',$courseCoachId)->column('coachName');
        $detail['coachName'] = implode(',',$coachName);
        $detail['courseCoachId'] = explode(',',$detail['courseCoachId']);

        $this->assign('detail', $detail);
        return $this->fetch('edit_course');
    }

    public function doEditCourse(){
        $params = input('post.');
        if (empty($params['courseType'])) {
            return json(array('code' => 500, 'msg' => 'error:课程类型为空'));
        }
        if (empty($params['courseTitle'])) {
            return json(array('code' => 500, 'msg' => 'error:课程名称为空'));
        }
        if (empty($params['coursePrice']) || $params['coursePrice'] <= 0) {
            return json(array('code' => 500, 'msg' => 'error:课程价格设置错误'));
        }
        if (empty($params['joint_number']) || $params['joint_number'] <= 0) {
            return json(array('code' => 500, 'msg' => 'error:课程节数设置错误'));
        }
        if (empty($params['courseCoachId'])) {
            return json(array('code' => 500, 'msg' => 'error:课程教练未设置'));
        }

        $courseCoachId = explode(',',$params['courseCoachId']);

        $coach = Db::name('coachs')
            ->where('coachId', 'in', $courseCoachId)
            ->where('coachIsDel', '=', '0')
            ->find();
        if (empty($coach)) {
            return json(array('code' => 500, 'msg' => 'error:选择的教练出错啦'));
        }

        if (!empty($params['courseLogo'])) {
            $params['courseLogo'] = strstr($params['courseLogo'],"public");
        }
        $catch = array(
            'courseType' => $params['courseType'],
            'courseShopId' => $coach['coachShopId'],
            'courseCoachId' => $params['courseCoachId'],
            'courseLogo' => !empty($params['courseLogo']) ? config('site_url.site_url') . "/" . $params['courseLogo'] : config('site_url.site_url') . "/public/images/logo.png",
            'courseTitle' => $params['courseTitle'],
            'courseDescribe' => !empty($params['courseDescribe']) ? $params['courseDescribe'] : false,
            'coursePrice' => $params['coursePrice'],
            'courseSort' => $params['courseSort'],
            'courseStatus' => $params['courseStatus'],
            'joint_number' => $params['joint_number'],
        );

        Db::name('coach_course')->where('courseId', '=', $params['courseId'])->save($catch);
        return json(array('code' => 200, 'msg' => 'success:编辑成功'));
    }

    public function delCourse(){
        $del_id = input('del_id');

        Db::name('coach_course')->where('courseId', '=', $del_id)->save(array(
            'courseIsDel' => '1',
        ));
        return json(array('code' => 200, 'msg' => '操作成功'));
    }

    public function coach_subscribe(){

        //判断时间是否已过，然后改变状态
        $subscribe_yi = Db::name('order_coach_subscribe')->where('orderStatus',1)->select();
        if($subscribe_yi){
            foreach($subscribe_yi as $v){
                $orderTimePeriodType = explode(',',$v['orderTimePeriodType']);
                $timePeriod = config('timePeriod')[max($orderTimePeriodType)-1];
                $time = strtotime(date('Y-m-d',$v['orderDate']).' '.$timePeriod['endTime']);
                if(time()>$time){
                    $orderSubscribeId = $v['orderCoachSubscribeId'];
                    $data = Db::name('order_coach_subscribe')->where('orderCoachSubscribeId',$orderSubscribeId)->update(['orderStatus' => 2]);
                    if($data){

                        Db::name('user_make_course')->where('userMakeCourseId',$v['userMakeCourseId'])->update(['makeCourseStatus'=>2]);
                    }

                }
            }
        }

        $makeCourseStatus = C('makeCourseStatus');
        $this->assign('makeCourseStatus',$makeCourseStatus);
        return $this->fetch();
    }

    public function ajax_coach_subscribe(){

        $params = input('post.');
        $page = input('page', '1');

        $where = array();
        if (isset($params['keywords']) && !empty($params['keywords'])) {
            $where['cc.courseTitle'] = array('like', '%'.$params['keywords'].'%');
        }

        if($params['makeCourseStatus'] != -2){
            $where['a.makeCourseStatus'] = $params['makeCourseStatus'];
        }else{
            $where['a.makeCourseStatus'] = ['in',[-1,1,2,3,4]];
        }

        $count = Db::name('user_make_course')->alias('a')
            ->join('order_course c', 'a.orderCourseId = c.orderCourseId')
            ->join('coach_course cc', 'cc.courseId = c.orderCoachCourseId')
            ->join('user u', 'u.userId = a.userId')
            ->where($where)
            ->count();
        $list = Db::name('user_make_course')->alias('a')
            ->join('order_course c', 'a.orderCourseId = c.orderCourseId')
            ->join('coach_course cc', 'cc.courseId = c.orderCoachCourseId')
            ->join('user u', 'u.userId = a.userId')
            ->where($where)
            ->field('a.*,cc.courseTitle,u.nickName')
            ->page($page, $this->listRows)->select();
        if($list){
            foreach($list as $k=>$v){
                $list[$k]['reservationTime'] = $v['reservationTime']?date('Y-m-d H:i',$v['reservationTime']):'';
                $list[$k]['makeCourseStatusName'] = C('makeCourseStatus')[$v['makeCourseStatus']];
                $list[$k]['timeSlot'] = $v['timeSlot'] == 1?'上午':'下午';
            }
        }

        $this->assign('list', $list);

        $ajaxPage = new AjaxPage($count, $this->listRows);
        $show = $ajaxPage->show();
        $this->assign('page', $show);

        return $this->fetch();
    }

    public function change_status(){

        $userMakeCourseId = input('userMakeCourseId');

        $makeCourseStatus = C('makeCourseStatus');
        $this->assign('makeCourseStatus',$makeCourseStatus);
        $this->assign('userMakeCourseId', $userMakeCourseId);

        return $this->fetch();
    }

    public function add_change_status(){

        $params = input('post.');
        if (empty($params['userMakeCourseId'])) {
            return json(array('code' => 500, 'msg' => 'error:id不能为空'));
        }
        if (empty($params['makeCourseStatus'])) {
            return json(array('code' => 500, 'msg' => 'error:请选择要变更的状态'));
        }

        $data = Db::name('user_make_course')->where('userMakeCourseId',$params['userMakeCourseId'])->update(['makeCourseStatus'=>$params['makeCourseStatus']]);
        if($params['makeCourseStatus'] == 3){
            Db::name('order_coach_subscribe')->where('userMakeCourseId',$params['userMakeCourseId'])->update(['orderStatus'=>2]);
        }
        return json(array('code' => 200, 'msg' => '操作成功','data'=>$data));

    }
}